package com.base.web.socket.controller.api;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.base.common.sys.entity.SysUserEntity;
import com.base.common.sys.service.SysUserService;
import com.base.common.utils.R;

@RequestMapping("/api/sys")
@Controller
public class SysUserApiController {
	
	@Resource
	private SysUserService sysUserService;
	
	/**
	 * 登录用户，账号不存在就注册
	 * @param entity
	 * @return
	 */
	@PostMapping("/login")
	@ResponseBody
	public R login(SysUserEntity entity, HttpServletRequest request) {
		if(StringUtils.isBlank(entity.getUsername()) || StringUtils.isBlank(entity.getPassword())) {
			return R.error("请输入账号或密码！");
		}
		entity.setName(entity.getUsername());
		SysUserEntity user = sysUserService.findByName(entity);
		
		if(null == user) {
			entity.setStatus(1);
			entity.setImg("static/img/fire-1.jpg");
			sysUserService.insert(entity); //新增返回主键
			user = entity;
		}else if(!entity.getPassword().equals(user.getPassword())){
			return R.error("密码错误或账号已存在！");
		}
		
		if(null == user.getId()) {
			return R.error("登录失败！");
		}
		return R.ok().put("username", user.getName()).put("userId", user.getId()).put("userImg", user.getImg());
	}
	
	@GetMapping("/findUserInfo")
	@ResponseBody
	public R getUserInfo(Integer userId, HttpServletResponse response) {
		if(null == userId) {
			return R.error("获取好友信息失败！");
		}
		
		SysUserEntity user = sysUserService.findById(userId);
		return R.ok().put("user", user);
	}
	/**
	 * 获取用户列表
	 * @param userId
	 * @return
	 */
	@GetMapping("/findUserList")
	@ResponseBody
	public R getUserList(Integer userId, HttpServletResponse response) {
		List<SysUserEntity> list = sysUserService.findByEntity(new SysUserEntity());
		SysUserEntity rme = null;
		for (int i = 0; i < list.size(); i++) {
			if(list.get(i).getId().equals(userId)) {
				rme = list.get(i);
			}
		}
		if(null != rme) {
			list.remove(rme);
		}
		return R.ok().put("userList", list);
	}
	
	
	@PostMapping("/uptUserInfo")
	@ResponseBody
	public R uptUserInfo(Integer userId, String type, String info) {
		if("user".equals(type)) {
			SysUserEntity upt = new SysUserEntity();
			upt.setId(userId);
			upt.setName(info);
			sysUserService.updateById(upt);
		}
		
		return R.ok();
	}
	
}
